<?php

namespace App\Store\Controllers\Goods;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Goods\GoodsCheck;
use App\Store\Models\Goods\GoodsCheckInfolist;
use App\Store\Models\Goods\GoodsStockList;
use Illuminate\Http\Request;
use App\Store\Validate\Goods\GoodsCheck as ValidateGoodsGoodsCheck;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 盘点
 */
class GoodsCheckController extends Controller
{
    /**
     * 店长端，盘点自己门店的货
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['title', 'remark', 'goods_category_ids', 'goods_category_names', 'goods_cabinetgroup_ids', 'goods_cabinetgroup_names', 'goods_style_ids', 'goods_style_names', 'goods_brand_id']);
        $Validate = new ValidateGoodsGoodsCheck();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $goods_category_ids = $req_data['goods_category_ids'];
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);

        $goods_style_ids = $req_data['goods_style_ids'];
        $goods_style_ids = is_array($goods_style_ids) ? $goods_style_ids : (is_array(json_decode($goods_style_ids, true)) ? json_decode($goods_style_ids, true) : []);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = $accountinfo['store_ids'];


        $categoryList = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
            ->get()
            ->pluck(null, 'id')
            ->toArray();


        $virtuallCate = [];
        foreach ($categoryList as $item) {
            if ($item['is_virtually'] == 1) {
                $virtuallCate[] = $item['id'];
            }
        }


        //获取盘点商品
        $query = GoodsStockList::query()
            ->where(['cp_id' => $cp_id, 'store_id' => $store_id, 'is_del' => 1])
            ->where('count', '>', 0)
            ->when(!empty($virtuallCate), function ($query) use ($virtuallCate) {
                $query->whereNotIn('goods_category_id', $virtuallCate);
            });
        if (count($goods_category_ids) >= 1) {
            $query = $query->whereIn('goods_category_id', $goods_category_ids);
        }

        //品牌
        if (!empty($request['goods_brand_id'])) {
            $query = $query->where('goods_brand_id', $req_data['goods_brand_id']);
        }

        //款式
        if (count($goods_style_ids) >= 1) {
            $query = $query->whereIn('goods_style_id', $goods_style_ids);
        }
        $goods_stock_list = $query->get()->toArray();

        if (empty($req_data['goods_category_ids']) && $req_data['goods_cabinetgroup_ids']) {
            return response()->json(['code' => '001', 'msg' => '该柜组下商品类别为空，无法创建！']);
        }


        DB::beginTransaction();
        try {
            $goods_check['cp_id'] = $cp_id;
            $goods_check['store_id'] = $store_id;
            $goods_check['code'] = StoreCommon::createOrderSn();
            $goods_check['title'] = $req_data['title'];
            if (empty($req_data['goods_category_ids']) && empty($req_data['goods_style_ids']) && empty($req_data['goods_brand_id']) && empty($req_data['goods_cabinetgroup_ids'])) {
                $check_type = 1;
            } else {
                $check_type = 2;
            }
            $goods_check['check_type'] = $check_type;
            $goods_check['remark'] = $req_data['remark'];
            $goods_check['goods_category_ids'] = json_encode($req_data['goods_category_ids'] ?? [], true);
            $goods_check['goods_category_names'] = str_replace(',', '，', $req_data['goods_category_names']);
            $goods_check['goods_style_ids'] = json_encode($req_data['goods_style_ids'] ?? [], true);
            $goods_check['goods_style_names'] = str_replace(',', '，', $req_data['goods_style_names']);
            $goods_check['goods_brand_id'] = !empty($req_data['goods_brand_id']) ? $req_data['goods_brand_id'] : 0;
            $goods_check['goods_cabinetgroup_ids'] = json_encode($req_data['goods_cabinetgroup_ids'] ?? [], true);
            $goods_check['goods_cabinetgroup_names'] = str_replace(',', '，', $req_data['goods_cabinetgroup_names']);
            $goods_check['create_account_id'] = $accountinfo['id'];
            $goods_check['create_account_real_name'] = $accountinfo['real_name'];
            $goods_check['create_at'] = time();

            $p_id = GoodsCheck::query()->create($goods_check)->id;


            $goods_check_infolist = [];
            if ($goods_stock_list) {
                foreach ($goods_stock_list as $k => $v) {
                    $goods_category = $categoryList[$v['goods_category_id']] ?? [];
                    $goods_check_infolist[$k]['total_price'] = $v['count'] * ($v['label_price']??0);
                    $goods_check_infolist[$k]['cp_id'] = $cp_id;
                    $goods_check_infolist[$k]['p_id'] = $p_id;
                    $goods_check_infolist[$k]['store_id'] = $store_id;
                    $goods_check_infolist[$k]['is_gram'] = $goods_category['is_gram']??0;
                    $goods_check_infolist[$k]['goods_style_id'] = $v['goods_style_id'];
                    $goods_check_infolist[$k]['goods_sn_code'] = $v['goods_sn_code'];
                    $goods_check_infolist[$k]['goods_name'] = $v['goods_name'];
                    $goods_check_infolist[$k]['goods_category_id'] = $v['goods_category_id'];
                    $goods_check_infolist[$k]['count'] = $v['count'];
                    $goods_check_infolist[$k]['label_price'] = $v['label_price'];
                    $goods_check_infolist[$k]['is_code_more'] = $v['is_code_more'];
                    $goods_check_infolist[$k]['netglod_weight'] = $v['total_netglod_weight'];
                    $goods_check_infolist[$k]['create_account_id'] = $accountinfo['id'];
                    $goods_check_infolist[$k]['create_account_real_name'] = $accountinfo['real_name'];
                    $goods_check_infolist[$k]['create_at'] = time();
                    $goods_check_infolist[$k]['total_weight'] = $v['total_netglod_weight'];
                }
            }

            $checkBatches = array_chunk($goods_check_infolist, 1000);
            foreach ($checkBatches as $batch) {
                GoodsCheckInfolist::query()->insert($batch);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '添加失败' . $e->getLine() . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '添加成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsCheck::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function getone(Request $request)
    {
        $one = GoodsCheck::where(['id' => $request['id']])->first();
        if ($one) {
            $one = $one->toArray();
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $one]);
        }
        return response()->json(['code' => '001', 'msg' => '获取失败']);
    }

    /**
     * 列表导出
     */
    public function doexport(Request $request)
    {
        $list = GoodsCheck::getList($request)['list'];

        // 1未盘点，2盘点中，3已盘点
        $status = $request['status'] ?? 0;
        if ($status == 1) {
            $start_store = '盘点管理(未盘)';
        } elseif ($status == 2) {
            $start_store = '盘点管理(部分盘)';
        } else {
            $start_store = '盘点管理(已盘)';
        }
        $row = [
            ['start_store' => $start_store],
            [
                'start_store' => '所属门店',
                'code' => '编码',
                'title' => '标题',
                'check_type' => '盘点类型',
                'goods_category_name' => '商品类别',
                'brand_name' => '品牌',
                'goods_style_name' => '款式',
                'remark' => '说明',
                'goods_cabinetgroup_names' => '柜台',
                'status' => '状态',
                'create_account_real_name' => '创建人',
                'create_at' => '创建时间',
                'update_account_real_name' => '更新人',
                'update_at' => '更新时间',
            ]];

        $exceldata = [];
        foreach ($list as $val) {
            if ($val['check_type'] == 1) {
                $check_type = '全部盘点';
            } else {
                $check_type = '部分盘点';
            }

            if ($val['status'] == 1) {
                $status = '未盘点';
            } elseif ($val['status'] == 2) {
                $status = '盘点中';
            } else {
                $status = '已盘点';
            }
            $exceldata[] = [
                'start_store' => $val['storeinfo']['store_name'] ?? '',
                'code' => $val['code'],
                'title' => $val['title'],
                'check_type' => $check_type,
                'goods_category_name' => $val['goods_category_names'] ?? '',
                'brand_name' => $val['brand']['brand_name'] ?? '',
                'goods_style_name' => $val['goods_style_names'],
                'remark' => $val['remark'],
                'goods_cabinetgroup_names' => $val['goods_cabinetgroup_names'],
                'status' => $status,
                'create_account_real_name' => $val['create_account_real_name'],
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
            ];
        }

        $filename = '盘点单信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $req_data = $request->only(['id']);
        $Validate = new ValidateGoodsGoodsCheck('del');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        DB::beginTransaction();
        try {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);

            GoodsCheck::where('id', $req_data['id'])->update([
                'is_del' => 2,
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
                'update_at' => time(),
            ]);

            GoodsCheckInfolist::where('p_id', $req_data['id'])->update([
                'is_del' => 2,
                'update_account_id' => $accountinfo['id'],
                'update_account_real_name' => $accountinfo['real_name'],
                'update_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    /**
     * 明细
     */
    public function getlistsummary(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);

        $cp_id = $accountinfo['cp_id'];
        $store_ids = $accountinfo['store_ids'] ?? [];

        $is_check = $request['is_check'] ?? 0;
        $where = [];
        if ($is_check > 0) {
            $where = ['is_check' => $is_check];
        }
        $where1 = [];
        $goods_category_id = $request['goods_category_id'] ?? 0;
        if ($goods_category_id > 0) {
            $where1 = ['goods_category_id' => $goods_category_id];
        }
        $where2 = [];
        $goods_style_id = $request['goods_style_id'] ?? 0;
        if ($goods_style_id > 0) {
            $where2 = ['goods_style_id' => $goods_style_id];
        }

        $list = GoodsCheckInfolist::with(['goods_category' => function ($query) {
            $query->where('is_del', 1);
        }])->where([
                'p_id' => $request['p_id']
            ] + $where1)
            ->where('count', '>', 0)
            ->select('goods_category_id', DB::raw('sum(count) as count, sum(count_check) as count_check, sum(netglod_weight) as total_weight, sum(total_weight_check) as total_weight_check, sum(total_price) as total_price, sum(total_price_check) as total_price_check, sum(label_price) as total_label_price'))
            ->groupBy('goods_category_id')->get();
        if ($list) {
            $list = $list->toArray();
            foreach ($list as $key => $item) {
                if (!isset($item['goods_category'])) {
                    unset($list[$key]);
                }
            }
        }


        if ($list) {
            $list = array_values($list);
            // 根据类型获取数据
            foreach ($list as $k => $v) {
                $query = GoodsCheckInfolist::with('goods_style')->where([
                        'p_id' => $request['p_id'],
                        'goods_category_id' => $v['goods_category_id']
                    ] + $where + $where2);
                $list[$k]['style_infolist'] = $query->select('goods_style_id', DB::raw('sum(count) as count, sum(count_check) as count_check, sum(total_weight) as total_weight, sum(total_weight_check) as total_weight_check, sum(total_price) as total_price, sum(total_price_check) as total_price_check'), 'is_check', 'label_price')->where('count', '>', 0)->groupBy('goods_style_id')->get()->toArray();
            }


            // 过滤虚拟的数据
            $virtuallyCate = GoodsCategory::query()
                ->where(['cp_id' => $cp_id, 'is_del' => 1, 'is_virtually' => 1])
                ->when(!empty($store_ids), function ($query) use ($store_ids) {
                    if (is_array($store_ids)) {
                        $query->whereIn('store_id', $store_ids);
                    } else {
                        $query->where('store_id', $store_ids);
                    }
                })
                ->get(['id'])
                ->pluck('id')
                ->toArray();

            $data = [];
            foreach ($list as $val) {
                $goods_category_id = $val['goods_category']['id'] ?? 0;
                foreach ($val['style_infolist'] as $v) {
                    if (!in_array($goods_category_id, $virtuallyCate)) {
                        $data[] = [
                            'goods_category_id' => $val['goods_category']['id'] ?? '',
                            'goods_category' => $val['goods_category']['category_name'] ?? '',
                            'total_count' => $val['count'],
                            'total_count_check' => $val['count_check'],
                            'total_weight' => $val['total_weight'],
                            'total_weight_check' => $val['total_weight_check'],
                            'total_price' => $val['total_price'],
                            'total_label_price' => $val['total_label_price'],
                            'total_price_check' => $val['total_price_check'],
                            'style_id' => $v['goods_style_id'],
                            'style_name' => $v['goods_style']['style_name'] ?? '',
                            'count' => $v['count'],
                            'count_check' => $v['count_check'],
                            'weight' => $v['total_weight'],
                            'weight_check' => $v['total_weight_check'],
                            'label_price' => $v['label_price'],
                            'price' => $v['total_price'],
                            'price_check' => $v['total_price_check'],
                            'is_check' => $v['is_check'],
                        ];
                    }

                }
            }
            return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => []]);
    }

    public function doexportsummary(Request $request)
    {

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_ids = $accountinfo['store_ids'] ?? [];

        $list = GoodsCheckInfolist::with(['goods_category' => function ($query) {
            $query->where('is_del', 1);
        }])->where(['p_id' => $request['p_id']])
            ->where('count', '>', 0)
            ->select('goods_category_id', DB::raw('sum(count) as count, sum(count_check) as count_check, sum(netglod_weight) as total_weight, sum(total_weight_check) as total_weight_check, sum(total_price) as total_price, sum(total_price_check) as total_price_check'))
            ->groupBy('goods_category_id')->get();
        if ($list) {
            $list = $list->toArray();
            foreach ($list as $key => $item) {
                if (!isset($item['goods_category'])) {
                    unset($list[$key]);
                }
            }
        }

        // 过滤虚拟的数据
        $virtuallyCate = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'is_virtually' => 1])
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', $store_ids);
                }
            })
            ->get(['id'])
            ->pluck('id')
            ->toArray();

        if ($list) {
            $list = array_values($list);
            // 根据类型获取数据
            foreach ($list as $k => $v) {
                $query = GoodsCheckInfolist::with('goods_style')->where([
                    'p_id' => $request['p_id'],
                    'goods_category_id' => $v['goods_category_id']
                ]);
                $list[$k]['style_infolist'] = $query->select('goods_style_id', DB::raw('sum(count) as count, sum(count_check) as count_check, sum(total_weight) as total_weight, sum(total_weight_check) as total_weight_check, sum(total_price) as total_price, sum(total_price_check) as total_price_check'), 'is_check')->groupBy('goods_style_id')->get()->toArray();
            }

            $row = [
                ['start_store' => '盘点明细'],
                [
                    'goods_category' => '商品类别',
                    'total_count' => '件数',
                    'total_count_check' => '已盘件数',
                    'total_count_diff' => '件差异数',
                    'total_weight' => '重量',
                    'total_weight_check' => '已盘重量',
                    'total_weight_diff' => '重量差异数',
                    'total_price' => '金额',
                    'total_price_check' => '已盘金额',
                    'style' => '款式',
                    'count' => '件数',
                    'count_check' => '已盘件数',
                    'count_diff' => '件差异数',
                    'weight' => '重量',
                    'weight_check' => '已盘重量',
                    'weight_diff' => '重量差异数',
                    'price' => '金额',
                    'price_check' => '已盘金额',
                    'is_check' => '状态',
                ]];

            $exceldata = [];
            $initcont = count($row) + 1;
            $mergecell = [];


            foreach ($list as $key => $val) {
                $goods_category_id = $val['goods_category']['id'] ?? 0;
                $mergecell[] = 'A' . $initcont . ':A' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'B' . $initcont . ':B' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'D' . $initcont . ':D' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'E' . $initcont . ':E' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'F' . $initcont . ':F' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'G' . $initcont . ':G' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'H' . $initcont . ':H' . $initcont + count($val['style_infolist']) - 1;
                $mergecell[] = 'I' . $initcont . ':I' . $initcont + count($val['style_infolist']) - 1;
                $initcont = $initcont + count($val['style_infolist']);

                foreach ($val['style_infolist'] as $k => $v) {
                    if ($v['is_check'] == 1) {
                        $is_check = '未盘点';
                    } else {
                        $is_check = '已盘点';
                    }

                    if (!in_array($goods_category_id, $virtuallyCate)) {
                        if ($k == 0) {
                            $exceldata[] = [
                                'goods_category' => $val['goods_category']['category_name'] ?? '',
                                'total_count' => $val['count'],
                                'total_count_check' => $val['count_check'],
                                'total_count_diff' => $val['count_check'] - $val['count'],
                                'total_weight' => $val['total_weight']/10000,
                                'total_weight_check' => $val['total_weight_check']/10000,
                                'total_weight_diff' => ($val['total_weight_check'] - $val['total_weight'])/10000,
                                'total_price' => $val['total_price'] / 100,
                                'total_price_check' => $val['total_price_check'] / 100,
                                'style' => $v['goods_style']['style_name']  ?? '',
                                'count' => $v['count'],
                                'count_check' => $v['count_check'],
                                'count_diff' => $v['count_check'] - $v['count'],
                                'weight' => $v['total_weight']/10000,
                                'weight_check' => $v['total_weight_check']/10000,
                                'weight_diff' => ($v['total_weight_check'] - $v['total_weight'])/10000,
                                'price' => $v['total_price'] / 100,
                                'price_check' => $v['total_price_check'] / 100,
                                'is_check' => $is_check,
                            ];
                        } else {
                            $exceldata[] = [
                                'goods_category' => is_numeric($val['goods_category']['category_name'] ?? '') ? 0 : '',
                                'total_count' => is_numeric($val['count']) ? 0 : '',
                                'total_count_check' => is_numeric($val['count_check']) ? 0 : '',
                                'total_count_diff' => is_numeric($val['count_check'] - $val['count']) ? 0 : '',
                                'total_weight' => is_numeric($val['total_weight']) ? 0 : '',
                                'total_weight_check' => is_numeric($val['total_weight_check']) ? 0 : '',
                                'total_weight_diff' => is_numeric($val['total_weight_check'] - $val['total_weight']) ? 0 : '',
                                'total_price' => is_numeric($val['total_price'] / 100) ? 0 : '',
                                'total_price_check' => is_numeric($val['total_price_check'] / 100) ? 0 : '',
                                'style' => $v['goods_style']['style_name']  ?? '',
                                'count' => $v['count'],
                                'count_check' => $v['count_check'],
                                'count_diff' => $v['count_check'] - $v['count'],
                                'weight' => $v['total_weight']/10000,
                                'weight_check' => $v['total_weight_check']/10000,
                                'weight_diff' => ($v['total_weight_check'] - $v['total_weight'])/10000,
                                'price' => $v['total_price'] / 100,
                                'price_check' => $v['total_price_check'] / 100,
                                'is_check' => $is_check,
                            ];
                        }
                    }


                }
            }


            $filename = '盘点单信息导出_' . time() . '.xlsx';
            return Excel::download(new CommonExcelExport($row, $exceldata, [], $mergecell), $filename);
        }
        return response()->json(['code' => '001', 'msg' => '下载失败']);
    }

    /**
     * 完成
     */
    public function summarycheck(Request $request)
    {
        $req_data = $request->only(['p_id', 'goods_category_id', 'goods_style_id']);
        $Validate = new ValidateGoodsGoodsCheck('summarycheck');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        GoodsCheckInfolist::where([
            'p_id' => $req_data['p_id'],
            'goods_category_id' => $req_data['goods_category_id'],
            'goods_style_id' => $req_data['goods_style_id']
        ])->update([
            'is_check' => 2,
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'update_at' => time(),
        ]);

        $list = GoodsCheckInfolist::where(['p_id' => $req_data['p_id']])->get()->toArray();
        $status = 3;
        foreach ($list as $item) {
            if ($item['is_check'] == 1) {
                $status = 2;
            }
        }
        GoodsCheck::where(['id' => $req_data['p_id']])->update([
            'status' => $status,
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'update_at' => time(),
        ]);

        return response()->json(['code' => '000', 'msg' => '完成成功']);
    }

    /**
     * 一键完成
     */
    public function onekeycheck(Request $request)
    {
        $req_data = $request->only(['p_id']);
        $Validate = new ValidateGoodsGoodsCheck('onekeycheck');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        GoodsCheck::where(['id' => $req_data['p_id']])->update([
            'status' => 3,
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'update_at' => time(),
        ]);

        GoodsCheckInfolist::where([
            'p_id' => $req_data['p_id']
        ])->update([
            'is_check' => 2,
            'update_account_id' => $accountinfo['id'],
            'update_account_real_name' => $accountinfo['real_name'],
            'update_at' => time(),
        ]);
        return response()->json(['code' => '000', 'msg' => '完成成功']);
    }

    /**
     * 明细列表
     */
    public function getinfolist(Request $request)
    {
        $list = GoodsCheckInfolist::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 明细导出
     */
    public function doexportinfolist(Request $request)
    {

        $is_check = $request->post('is_check');
        $list = GoodsCheckInfolist::getList($request)['list'];
        $start_store = $is_check == 2 ? '已盘明细' : '未盘明细';
        if ($list) {
            $row = [
                ['start_store' => $start_store],
                [
                    'goods_name' => '商品名称',
                    'goods_category' => '类别',
                    'goods_style' => '款式',
                    'goods_sn_code' => '条码',
                    'total_price' => '标价',
                    'total_weight' => '重量',
                    'count' => '库存数',
                    'count_check' => '盘点数',
                    'count_diff' => '差异数',
                    'update_account_real_name' => '盘点人',
                    'is_check' => '是否盘点',
                ]];

            $exceldata = [];
            foreach ($list as $val) {
                if ($val['is_check'] == 1) {
                    $is_check = '未盘点';
                } else {
                    $is_check = '已盘点';
                }

                $exceldata[] = [
                    'goods_name' => $val['goods_name'],
                    'goods_category' => $val['goods_category']['category_name'],
                    'goods_style' => $val['goods_style']['style_name'] ?? '',
                    'goods_sn_code' => $val['goods_sn_code'],
                    'total_price' => $val['label_price'] / 100,
                    'total_weight' => (string)$val['total_weight'],
                    'count' => $val['count'],
                    'count_check' => $val['count_check'],
                    'count_diff' => $val['count_check'] - $val['count'],
                    'update_account_real_name' => $val['update_account_real_name'],
                    'is_check' => $is_check,
                ];
            }

            $filename = '盘点单信息导出_' . time() . '.xlsx';
            return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
        }
        return response()->json(['code' => '001', 'msg' => '下载失败']);
    }


    /**
     * 盘点计划获取
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkget(Request $request)
    {

        $goods_sn_code = $request['goods_sn_code'] ?? '';
        $count_check = $request['count_check'] ?? 1;
        $total_weight_check = $request['total_weight_check'] ?? 0;
        $is_view = $request['is_view'] ?? 0;
        if ($goods_sn_code != '') {
            $one = GoodsCheckInfolist::query()->where([
                'p_id' => $request['p_id'],
                'goods_sn_code' => $request['goods_sn_code']
            ])->first();

            if (!$one) {
                return response()->json(['code' => '001', 'msg' => '盘点失败，商品不存在']);
            }
            $one = $one->toArray();
            $one['count_check'] = $count_check;
            $one['total_weight_check'] = 0;
            if ($one['is_code_more'] == 1) {
                $one['total_weight_check'] = bcdiv($one['total_weight'], $one['count'], 3) * $count_check;
            }
//            else {
//                if ($total_weight_check == 0 &&$is_view==1) {
//                    return response()->json(['code' => '001', 'msg' => '一码多货商品盘点重量不能为空']);
//                }
//                $one['total_weight_check'] = $total_weight_check;
//            }

            $one['total_price_check'] = $count_check * $one['label_price'] ?? 0;

            if ($one['is_check'] == 2) {
                return response()->json(['code' => '001', 'msg' => '商品已盘点', 'data' => $one]);
            }
        }

        // 盘点总件数
        $one['sum_count'] = GoodsCheckInfolist::query()
            ->where(['p_id' => $request['p_id'], 'is_check' => 2, 'is_del' => 1])
            ->sum('count');

        $one['sum_weight_check'] = GoodsCheckInfolist::query()
            ->where(['p_id' => $request['p_id'], 'is_check' => 2, 'is_del' => 1])
            ->sum('total_weight_check');

        $one['sum_price_check'] = GoodsCheckInfolist::query()
            ->where(['p_id' => $request['p_id'], 'is_check' => 2, 'is_del' => 1])
            ->sum('total_price_check');

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $one]);
    }

    /**
     * 盘点
     */
    public function checkset(Request $request)
    {
        $req_data = $request->only(['p_id', 'count_check', 'weight_check', 'goods_sn_code']);
        $Validate = new ValidateGoodsGoodsCheck('checkset');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        DB::beginTransaction();
        try {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $one = GoodsCheckInfolist::where(['p_id' => $req_data['p_id'], 'goods_sn_code' => $req_data['goods_sn_code']])->first();
            if (!$one) {
                return response()->json(['code' => '001', 'msg' => '盘点商品为空']);
            }
            $one = $one->toArray();

            if ($one['is_code_more'] == 1) {
                $total_weight_check = bcdiv($one['total_weight'], $one['count'], 3) * $req_data['count_check'];
            } else {
                // 一码多货
                if (empty($req_data['weight_check'])) {
                    return response()->json(['code' => '001', 'msg' => '一码多货商品盘点重量不能为空']);
                }
                $total_weight_check = $req_data['weight_check'];
            }

            $total_price_check = $req_data['count_check'] * $one['label_price'] ?? 0;
            GoodsCheckInfolist::query()->where([
                'id' => $one['id']])
                ->update([
                    'is_check' => 2,
                    'count_check' => $req_data['count_check'],
                    'total_weight_check' => $total_weight_check,
                    'total_price_check' => $total_price_check,
                    'update_account_id' => $accountinfo['id'],
                    'update_account_real_name' => $accountinfo['real_name'],
                    'update_at' => time(),
                ]);

            // 更新盘点单状态
            $status = 3;
            $list = GoodsCheckInfolist::where(['p_id' => $req_data['p_id']])->get()->toArray();;
            if ($list) {
                foreach ($list as $item) {
                    if ($item['is_check'] == 1) {
                        $status = 2;
                        break;
                    }
                }
                GoodsCheck::where(['id' => $req_data['p_id']])
                    ->update([
                        'status' => $status,
                        'update_account_id' => $accountinfo['id'],
                        'update_account_real_name' => $accountinfo['real_name'],
                        'update_at' => time(),
                    ]);
            }

            // 盘点总件数
            $one['sum_count'] = GoodsCheckInfolist::query()->where(['p_id' => $one['p_id'], 'is_check' => 2, 'is_del' => 1])->sum('count_check');
            $one['sum_weight_check'] = GoodsCheckInfolist::query()->where(['p_id' => $one['p_id'], 'is_check' => 2, 'is_del' => 1])->sum('total_weight_check');
            $one['sum_price_check'] = GoodsCheckInfolist::query()->where(['p_id' => $one['p_id'], 'is_check' => 2, 'is_del' => 1])->sum('total_price_check');

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '盘点失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '盘点成功', 'data' => $one]);
    }

    /**
     * 盘点结果
     */
    public function getcheckresult(Request $request)
    {
        $result = $request['result'];
        $request['isgetall'] = 1;
        $list = GoodsCheckInfolist::getListResult($request);
        $arr = [];
        foreach ($list['list'] as $v) {
            // is_code_more 1否 2是
            // 非一码多货按照件数差异数判断
            // 一码多货按照重量差异数判断
            if ($result == 1) {
                if ($v['is_code_more'] == 1) {
                    if (($v['count_check'] - $v['count']) > 0) {
                        $arr[] = $v;
                    }
                } else {
                    if (($v['total_weight_check'] - $v['total_weight']) > 0) {
                        $arr[] = $v;
                    }
                }
            } else {
                if ($v['is_code_more'] == 1) {
                    if (($v['count_check'] - $v['count']) < 0) {
                        $arr[] = $v;
                    }
                } else {
                    if (($v['total_weight_check'] - $v['total_weight']) < 0) {
                        $arr[] = $v;
                    }
                }
            }
        }

        $data['list'] = $arr;
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    public function doexportresult(Request $request)
    {
        $result = $request['result'];
        $request['isgetall'] = 1;
        $list = GoodsCheckInfolist::getListResult($request);
        $arr = [];
        foreach ($list['list'] as $v) {
            // is_code_more 1否 2是
            // 非一码多货按照件数差异数判断
            // 一码多货按照重量差异数判断
            if ($result == 1) {
                if ($v['is_code_more'] == 1) {
                    if (($v['count_check'] - $v['count']) > 0) {
                        $arr[] = $v;
                    }
                } else {
                    if (($v['total_weight_check'] - $v['total_weight']) > 0) {
                        $arr[] = $v;
                    }
                }
            } else {
                if ($v['is_code_more'] == 1) {
                    if (($v['count_check'] - $v['count']) < 0) {
                        $arr[] = $v;
                    }
                } else {
                    if (($v['total_weight_check'] - $v['total_weight']) < 0) {
                        $arr[] = $v;
                    }
                }
            }
        }

        $data['list'] = $arr;

        if ($data) {
            $row = [
                ['start_store' => '盘盈'],
                [
                    'goods_name' => '商品名称',
                    'goods_category' => '类别',
                    'goods_style' => '款式',
                    'goods_sn_code' => '条码',
                    'count_diff' => '件数',
                    'weight_diff' => '重量',
                    'price_diff' => '金额',
                ]];

            $exceldata = [];
            foreach ($data['list'] as $val) {
                $exceldata[] = [
                    'goods_name' => $val['goods_name'],
                    'goods_category' => $val['goods_category']['category_name'],
                    'goods_style' => $val['goods_style']['style_name'] ?? '',
                    'goods_sn_code' => $val['goods_sn_code'],
                    'count_diff' => $val['count_check'] - $val['count'],
                    'weight_diff' => $val['total_weight_check'] - $val['total_weight'],
                    'price_diff' => ($val['total_price_check'] - $val['total_price']) / 100,
                ];
            }

            $filename = '盘点单信息导出_' . time() . '.xlsx';
            return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
        }
        return response()->json(['code' => '001', 'msg' => '下载失败']);
    }

    /**
     * 通过柜组获取类别
     */
    public function getcategory(Request $request)
    {
        //根据柜组id查出商品类别
        $goods_cabinetgroup_ids = $request['goods_cabinetgroup_ids'];
        $goods_cabinetgroup_ids = is_array($goods_cabinetgroup_ids) ? $goods_cabinetgroup_ids : (is_array(json_decode($goods_cabinetgroup_ids, true)) ? json_decode($goods_cabinetgroup_ids, true) : []);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = $accountinfo['store_ids'];

        $category_list = GoodsCategory::whereIn('goods_cabinetgroup_id', $goods_cabinetgroup_ids)->where([
            'cp_id' => $cp_id,
            'store_id' => $store_id,
            'is_del' => 1
        ])->get();

        $category_id = [];
        if ($category_list) {
            $category_list = $category_list->toArray();
            foreach ($category_list as $item) {
                $category_id[] = $item['id'];
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '柜组下的商品类别为空']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $category_id]);
    }


    /**
     * 增加已盘的数量
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function incrStocktaking(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'count_check' => 'required',
            'total_weight_check' => 'required',
            'remark' => 'sometimes'
        ], [
            'id.required' => '盘点id不能为空',
            'total_weight_check.required' => '盘点数量不能为空',
            'weight_check.required' => '盘点重量不能为空',
        ]);

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id = (int)$accountinfo['store_ids'];

        if (empty($store_id)) {
            return response()->json(['code' => '001', 'msg' => '门店不存在不能操作']);
        }

        if (empty($params['count_check'])) {
            return response()->json(['code' => '001', 'msg' => '盘点数量不能为空']);
        }

        $where['id'] = $params['id'];
        $where['cp_id'] = $cp_id;
        $where['store_id'] = $store_id;

        $data = GoodsCheckInfolist::query()->where($where)->first();
        if (empty($data)) {
            return response()->json(['code' => '001', 'msg' => '盘点数据不存在']);
        }
        $data = $data->toArray();

        $total_price_check = $params['count_check'] * ($data['label_price'] ?? 0);
        $total_weight_check = 0;
        if ((int)$data['is_code_more'] == 2) {
            if (empty($params['total_weight_check']) || $params['total_weight_check'] <= 0) {
                return response()->json(['code' => '001', 'msg' => '一码多货已盘的重量不能为0']);
            }
            $total_weight_check = $params['total_weight_check'];
        } else {

            // 非一码多货
            if ($data['total_weight'] > 0 && $data['count'] > 0) {
                $total_weight_check = ($data['total_weight'] / $data['count']) * $params['count_check'];
                $total_weight_check = round($total_weight_check, 3);
            }
        }

        GoodsCheckInfolist::query()->where($where)->update([
            'count_check' => (int)$params['count_check'],
            'total_price_check' => $total_price_check,
            'remark' => $params['remark'] ?? '',
            'total_weight_check' => $total_weight_check
        ]);

        return response()->json(['code' => '000', 'msg' => '盘点操作成功']);
    }
}
